import time
import json
from flask import Blueprint,request, render_template,redirect, url_for,make_response,g
from flask_login import LoginManager,login_user,logout_user,login_required,current_user
# from flask_login.utils import _get_user
from .user import User,Captcha
from .jwt_token import genToken,verfiyToken
from .gen_captcha import vieCode
from io import BytesIO
# printrequestdata=False
from ..setting import *

from flask_cors import CORS
login_blue = Blueprint('login_page',__name__)
CORS(login_blue)

login_manager = LoginManager()
login_manager.login_view = 'helloworld'
# CurrentUser=User('','','')
@login_blue.record_once
def on_load(state):
  login_manager.init_app(state.app)

@login_manager.user_loader
def load_user(user_id):
	# if current_user.is_authenticated():
		# g.userId = current_user.get_id()
	# else:
		# g.userId = None 
	# return User.get(g.userId)
	return User.get(user_id)
@login_manager.request_loader
def load_user_from_request(request):
	token = request.headers.get('Authorization')
	if token == None:
		return None

	payload = verfiyToken(token)
	if payload != None:
		user = User.queryUser(payload['data']['username'])
	else:
		user = None
	# print('==============================================================================',user.userId,user.username)
	return user

# http://127.0.0.1:8080/Imagecaptcha.jpg?uuid=46cfceb8-fd57-4cd7-8bd7-3115559cda14
@login_blue.route('/captcha.jpg')
def captcha():
	uuid = request.args.get('uuid')
	img,code=vieCode().GetCodeImage(size=80, length=4)
	code=''.join(code)
	# print(uuid,code)
	# print(img)
	# img.show()
	file = BytesIO()
	img.save(file, format="JPEG")
	data=file.getvalue()
	resp = make_response(data)
	resp.headers["Content-Type"]  = "image/jpg"
	Captcha(uuid,code).save()
	return resp
# http://127.0.0.1:5000/test
@login_blue.route('/sys/test')
def testPage():
  returnData = {'code': 0, 'msg': 'success', 'data': 'test not reqired login' }
  return json.dumps(returnData),200

@login_blue.route('/sys/first')
@login_required
def firstPage():
	# print(dir(current_user))
	# print(current_user.is_authenticated)
	# token = request.headers.get('Authorization')
	# print('token:',token)
	# print(current_user.get_id())
	# print(current_user.username)
	# print(current_user.password)
	returnData = {'code': 0, 'msg': 'success', 'data': 'First Blood(来自 id: ' + str(current_user.get_id())+' username:'+current_user.username+' password:'+current_user.password +')' }
	return json.dumps(returnData)
	# return json.dumps({'code': 0, 'msg': 'success', 'data': 'First Blood'+' username:'+current_user.username})
	# return json.dumps({'code': 0, 'msg': 'success', 'data': 'First Blood'})
	# return json.dumps({'code': 0, 'msg': 'success', 'data': 'First Blood'+g.username+'  '+str(g.userId)})
	pass
@login_blue.route('/sys/login', methods=['POST'])
def login():
	if printrequestdata:print(str(request.data, 'UTF-8'))
	if str(request.data, 'UTF-8'):
		d=json.loads(str(request.data, 'UTF-8'))
		if 'username' in d.keys():username = d['username']
		else:username=''
		if 'password' in d.keys():password = d['password']
		else:password=''
		if 'uuid' in d.keys():uuid = d['uuid']
		else:uuid=''
		if 'captcha' in d.keys():captcha = d['captcha']
		else:captcha=''
	else:
		username = request.form['username']
		password = request.form['password']
		# uuid = request.form['uuid']
		# captcha = request.form['captcha']
		uuid=''
		captcha=''
	if request.method == 'POST':
		print(username,password,uuid,captcha)
		user = User.queryUser(username)
		# CurrentUser=user
		# current_user=user
		if Captcha(uuid,captcha).verify():
		# if True:
			if (user != None) and (user.verifyPassword(password)):
				login_user(user)
				print('-----------------------------------login user------------------------------------')
				token = genToken({'username':username,'password':'******'})
				returnData = {'code': 0, 'msg': 'success', 'token':token}
				return json.dumps(returnData)
			else :
				returnData = {'code': 1, 'msg': 'success', 'data': 'username or password is not correct' }
				return json.dumps(returnData)  
		else:
			returnData = {'code': 1, 'msg': 'success', 'data': 'captcha is not correct' }
			return json.dumps(returnData) 
@login_blue.route('/sys/logout', methods=['GET','POST']) 
# @login_required
def logout():
	logout_user()
	returnData = {'code': 0, 'msg': 'success', 'data': ' Bye '}
	# returnData = {'code': 0, 'msg': 'success', 'data': ' Bye '+current_user.username}
	return json.dumps(returnData)